package lesson06;

import java.util.concurrent.TimeUnit;

/**
 * 两个线程交替打印,
 * 老师的代码是：先打印， 然后唤醒另一个线程，最后当前线程阻塞
 */
public class SynchronizedDemo {

    public static void main(String[] args) throws Exception {
        /*for (int i = 0; i < 100; i++) {
            System.out.println();
            TimeUnit.SECONDS.sleep(1);
            m1();
        }*/
        m1();
    }

    public static void m1(){
        char[] cI = "1234567".toCharArray();
        char[] cA = "ABCDEFG".toCharArray();

        Object lock = new Object();

        new Thread(() -> {

            synchronized (lock) {
                for (int i = 0; i < cA.length; i++) {
                    try {
                        lock.wait();
                        lock.notify();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.print(cA[i]);
                }
                // lock.notify();
            }
        }).start();

        new Thread(() -> {

            synchronized (lock) {
                for (int i = 0; i < cI.length; i++) {
                    try {
                        System.out.print(cI[i]);
                        lock.notify();
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                // lock.notify();
            }
        }).start();
    }

    public static void m2(){
        char[] cI = "1234567".toCharArray();
        char[] cA = "ABCDEFG".toCharArray();

        Object lock = new Object();

        new Thread(() -> {
            synchronized (lock) {
                for (int i = 0; i < cI.length; i++) {
                    System.out.print(cI[i]);
                    try {
                        lock.notify();
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                lock.notify();
            }
        }).start();

        new Thread(() -> {

            synchronized (lock) {
                for (int i = 0; i < cA.length; i++) {
                    System.out.print(cA[i]);
                    try {
                        lock.notify();
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                // lock.notify();
            }
        }).start();


    }
}
